<template>
  <div id="first-week-date">
    <div class="timeline-container">
      <Scroll :on-reach-bottom="handleReachBottom">
        <Timeline pending>
          <TimelineItem v-for="(item, index) in timelineData" :key="index" :color="index === 0 ? 'green' : 'blue'">
            <template v-if="index === 0">
              <Icon type="md-add-circle" slot="dot"/>
              <p class="operation pt-0 pb-0" v-if="!item.update">
                <Button class="add-btn" size="small" @click="item.update = true">新增</Button>
              </p>
            </template>
            <template v-else>
              <Icon v-if="item.studyYear === currStudyYear && item.semester === currSemester && item.firstWeekDate === currFirstWeekDate" type="md-ribbon" slot="dot"/>
              <p class="time">{{ item.firstWeekDate }}</p>
              <p class="content">
                {{ item.studyYear }} ~ {{ Number(item.studyYear) + 1 }}第{{ ['一', '二'][item.semester] }}学期{{ item.studyYear === currStudyYear && item.semester === currSemester && item.firstWeekDate === currFirstWeekDate ? '（目前第一周的日期）' : ''}}
              </p>
              <p class="operation" v-if="!item.update"
                 :style="{ pointerEvents: item.deleting ? 'none' : 'auto'}">
                <Button class="modify-btn" size="small" @click="item.update = true">修改</Button>
                <Poptip
                  v-if="!(item.studyYear === currStudyYear && item.semester === currSemester && item.firstWeekDate === currFirstWeekDate)"
                  confirm
                  title="确定删除该第一周日期吗？"
                  placement="bottom"
                  :options="popperOpts"
                  @on-ok="confirmDel(item)">
                  <Button :class="!item.deleting ? 'delete-btn' : ''" size="small" :type="item.deleting ? 'error' : 'default'" :loading="item.deleting">删除</Button>
                </Poptip>
              </p>
            </template>
            <Form v-show="item.update" ref="form" :style="{ pointerEvents: item.submiting ? 'none' : 'auto'}" :model="item.form" :rules="ruleValidate">
              <FormItem label="学年" prop="studyYear">
                <DatePicker
                  :value="item.form.studyYear"
                  type="year"
                  size="small"
                  confirm
                  clearable
                  :enabledPreventOverflow="datePickier.enabledPreventOverflow"
                  :options="datePickier.studyYearOpts"
                  placeholder="请选择学年"
                  @on-change="item.form.studyYear = $event"></DatePicker>
                <span v-show="item.form.studyYear">&nbsp;&nbsp;~&nbsp;&nbsp;{{ Number(item.form.studyYear) + 1 }} 学年</span>
              </FormItem>
              <FormItem label="学期" prop="semester">
                <RadioGroup v-model="item.form.semester">
                  <Radio :label="0" class="mr-10">第一学期</Radio>
                  <Radio :label="1">第二学期</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem label="第一周日期" prop="firstWeekDate">
                <DatePicker
                  :value="item.form.firstWeekDate"
                  type="date"
                  size="small"
                  confirm
                  clearable
                  :enabledPreventOverflow="datePickier.enabledPreventOverflow"
                  :options="datePickier.firstWeekDateOpts"
                  placeholder="请选择第一周的日期" @on-change="item.form.firstWeekDate = $event"></DatePicker>
              </FormItem>
              <FormItem>
                <Poptip
                  confirm
                  title="确定保存该第一周日期吗？"
                  placement="bottom"
                  :options="popperOpts"
                  @on-ok="handleSubmit(index)">
                  <Button class="mr-10" type="primary" size="small" :loading="item.submiting">保存</Button>
                </Poptip>
                <Button size="small" @click="item.update = false">取消</Button>
              </FormItem>
            </Form>
          </TimelineItem>
          <TimelineItem v-if="showMore">
            <a href="javascript:void(0);" @click="pageBuilder.pageSize += 5">查看更多</a>
          </TimelineItem>
        </Timeline>
      </Scroll>
    </div>
  </div>
</template>

<script>
import { getFirstWeekDateList, setFirstWeekDate, deleteFirstWeekDate, getCurrTermDateInfo } from '@/api/first-week-date'
export default {
  name: 'FirstWeekDate',
  data () {
    return {
      firstEnter: false,
      visiable: false,
      showMore: false,
      datePickier: {
        enabledPreventOverflow: false,
        studyYearOpts: {
          shortcuts: [{
            text: '今年',
            value () {
              return new Date()
            }
          }]
        },
        firstWeekDateOpts: {
          shortcuts: [{
            text: '今天',
            value () {
              return new Date()
            }
          }]
        }
      },
      pageBuilder: {
        pageSize: 5,
        pageNum: 1,
        order: [{
          studyYear: 'desc'
        }, {
          semester: 'desc'
        }]
      },
      timelineData: [],
      currStudyYear: '',
      currSemester: '',
      currFirstWeekDate: '',
      ruleValidate: {
        studyYear: [
          { required: true, message: '请选择学年', trigger: 'change' }
        ],
        semester: [
          { required: true, type: 'integer', message: '请选择学期', trigger: 'change' }
        ],
        firstWeekDate: [
          { required: true, message: '请选择第一周日期', trigger: 'change' }
        ]
      },
      popperOpts: {
        modifiers: {
          preventOverflow: {
            boundariesElement: 'scrollParent',
            enabled: false
          },
          hide: {
            enabled: false
          }
        }
      }
    }
  },
  methods: {
    // 获取第一周日期列表并赋值渲染
    async renderFirstWeekDateList (pageBuilder) {
      // 初始化数据
      this.$emit('triggerSpin', true)
      this.showMore = false
      try {
        let response = await getFirstWeekDateList(pageBuilder)
        let res = response.data
        this.timelineData = [{
          update: false,
          submiting: false,
          form: {
            studyYear: new Date().getFullYear().toString(),
            semester: 0,
            firstWeekDate: new Date().toLocaleDateString().replace(/\//g, '-')
          }
        }]
        if (res.code === 1) {
          if (res.data.content && res.data.content.length > 0) {
            // 处理数据并赋值绑定
            this.timelineData = this.timelineData.concat(res.data.content.map(item => {
              return Object.assign({}, item, {
                update: false,
                deleting: false,
                submiting: false,
                form: item
              })
            }))
            this.showMore = res.data.totalPages > 1
            this.$nextTick(() => {
              this.$emit('triggerSpin', false)
            })
          } else {
            this.$emit('triggerSpin', false)
          }
        } else {
          this.$emit('triggerSpin', false)
          this.$Notice.error({
            title: '列表加载失败',
            desc: '第一周日期列表加载失败！' + res.info
          })
        }
      } catch (error) {
        this.$Notice.error({
          title: '列表加载失败',
          desc: '第一周日期列表加载失败！请重试！'
        })
        console.log(error)
      }
    },
    // 提交保存
    handleSubmit (index) {
      this.$refs.form[index].validate((valid) => {
        if (valid) {
          this.timelineData[index].submiting = true
          setFirstWeekDate(this.timelineData[index].form).then(response => {
            this.timelineData[index].submiting = false
            let res = response.data
            if (res.code === 1) {
              this.$Notice.success({
                title: '提示',
                desc: '保存第一周日期成功！'
              })
              this.getCurrTermDateInfo()
              this.renderFirstWeekDateList(this.pageBuilder)
            } else {
              this.$Notice.error({
                title: '提示',
                desc: '保存第一周日期失败！' + res.info + '请重试！'
              })
            }
          }).catch(error => {
            this.timelineData[index].submiting = false
            this.$Notice.error({
              title: '提示',
              desc: '保存第一周日期失败！请重试！'
            })
            console.log(error)
          })
        } else {
          this.$Notice.error({
            title: '提示',
            desc: '保存失败，请先完善表单信息再重试！'
          })
        }
      })
    },
    // 确认删除
    confirmDel (item) {
      item.deleting = true
      deleteFirstWeekDate([item.id]).then(response => {
        let res = response.data
        item.deleting = false
        if (res.code === 1) {
          this.$Notice.success({
            title: '提示',
            desc: '删除所选的第一周日期成功！'
          })
          // 从当前状态重新加载表格
          this.renderFirstWeekDateList(this.pageBuilder)
        } else {
          this.$Notice.error({
            title: '提示',
            desc: '删除所选的第一周日期失败！' + res.info
          })
        }
      }).catch(error => {
        console.log(error)
        item.deleting = false
        this.$Notice.error({
          title: '提示',
          desc: '删除所选的第一周日期失败，请重试！'
        })
      })
    },
    // 滚动至底部时，触发加载更多数据
    handleReachBottom () {
      return new Promise((resolve, reject) => {
        try {
          let pageBuilder = JSON.parse(JSON.stringify(this.pageBuilder))
          pageBuilder.pageSize += 5
          this.showMore = false
          getFirstWeekDateList(pageBuilder).then(response => {
            let res = response.data
            this.timelineData = [{
              update: false,
              submiting: false,
              form: {
                studyYear: new Date().getFullYear().toString(),
                semester: 0,
                firstWeekDate: new Date().toLocaleDateString()
              }
            }]
            if (res.code === 1) {
              if (res.data.content && res.data.content.length > 0) {
                // 处理数据并赋值绑定
                this.timelineData = this.timelineData.concat(res.data.content.map(item => {
                  return Object.assign({}, item, {
                    update: false,
                    deleting: false,
                    submiting: false,
                    form: item
                  })
                }))
                this.showMore = res.data.totalPages > 1
                this.$nextTick(() => {
                  resolve(res)
                })
              }
            } else {
              this.$Notice.error({
                title: '列表加载失败',
                desc: '第一周日期列表加载失败！' + res.info
              })
              reject(res)
            }
          }).catch(error => {
            this.$Notice.error({
              title: '列表加载失败',
              desc: '第一周日期列表加载失败！请重试！'
            })
            reject(error)
          })
        } catch (error) {
          this.$Notice.error({
            title: '列表加载失败',
            desc: '第一周日期列表加载失败！请重试！'
          })
          reject(error)
        }
      })
    },
    async getCurrTermDateInfo () {
      try {
        let response = await getCurrTermDateInfo()
        let res = response.data
        if (res.code === 1) {
          this.currStudyYear = res.data.studyYear
          this.currSemester = res.data.semester
          this.currFirstWeekDate = res.data.firstWeekDate
        } else {
          this.currStudyYear = ''
          this.currSemester = ''
          this.currFirstWeekDate = ''
          this.$Notice.error({
            title: '获取数据失败',
            desc: '获取当前学年、学期和第一周日期失败！' + res.info + '请重试！'
          })
        }
      } catch (error) {
        this.currStudyYear = ''
        this.currSemester = ''
        this.currFirstWeekDate = ''
        this.$Notice.error({
          title: '获取数据失败',
          desc: '获取当前学年、学期和第一周日期失败！请重试！'
        })
      }
    }
  },
  created () {
    this.firstEnter = true
    this.$Notice.config({
      top: window.innerHeight / 3
    })
    this.getCurrTermDateInfo()
    this.renderFirstWeekDateList(this.pageBuilder)
  },
  mounted () {
  },
  activated () {
    if (!this.firstEnter) {
      this.$Notice.config({
        top: window.innerHeight / 3
      })
    }
  },
  deactivated () {
    this.firstEnter = false
    this.$Notice.destroy()
  },
  beforeDestroy () {
    this.$Notice.destroy()
  },
  watch: {
    pageBuilder: {
      handler: function (value) {
        this.renderFirstWeekDateList(value)
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
  #first-week-date {
    .timeline-container {
      .time {
        font-size: 16px;
        font-weight: bold;
      }
      .content {
        padding: 5px;
        font-size: 14px;
      }
      .operation {
        padding-top: 5px;
        padding-bottom: 5px;
      }
      .add-btn {
        color: #19be6b;
        border-color: #19be6b;
        margin-left: 5px;
        margin-right: 5px;

        &:hover {
          color: #fff;
          background-color: #19be6b;
        }

        &:focus {
          box-shadow: unset;
        }
      }

      .modify-btn {
        color: #2db7f5;
        border-color: #2db7f5;
        margin-left: 5px;
        margin-right: 5px;

        &:hover {
          color: #fff;
          background-color: #2db7f5;
        }

        &:focus {
          box-shadow: unset;
        }
      }

      .delete-btn {
        color: #ed4014;
        border-color: #ed4014;
        margin-left: 5px;
        margin-right: 5px;

        &:hover {
          color: #fff;
          background-color: #ed4014;
        }

        &:focus {
          box-shadow: unset;
        }
      }
    }
  }
</style>
<style lang="less">
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal{
      top: 0;
    }
  }
</style>
